﻿// 设置权限
var setAuthorize;
// 获取表单数据
var getFormData;
// 设置表单数据
var setFormData;
// 验证数据是否填写完整
var validForm;
var validBusinessData;
// 保存数据
var save;
var saveDraft;
//不可编辑
var setFormDisabled;

var isUpdate = false;

var bootstrap = function ($, learun) {
    "use strict";

    var userinfo;
    var companyId;
    var startTime;
    var endTime

    // 设置权限
    setAuthorize = function (data, isLook) {
        userinfo = learun.clientdata.get(['userinfo']);
        $("#createUsername").val(userinfo.user.realName);

        //项目类别
        $('#category').lrDataItemSelect({code: 'ProjectCategorys'});
        //项目属性
        $('#attribute').lrDataItemSelect({code: 'ProjectLevels'});
        //项目性质
        $('#nature').lrDataItemSelect({code: 'ProjectExistenceStatus'});
        $('#departmentId').lrDepartmentSelect({companyId: '', maxHeight: 100});
        // 单位选择
        $('#companyId').lrselect({
            type: 'tree',
            // placeholder: '请选择机构',
            height: 200,
            maxHeight: 200,
            // 是否允许搜索
            //allowSearch: true,
            select: function (item) {
                if (item && item.value != '-1') {
                    companyId = item.value;
                    // 负责部门
                    $('#departmentId').lrDepartmentSelect({companyId: companyId, maxHeight: 100});
                }
            }
        });
        $('#companyId').lrselectRefresh({
            // 访问数据接口地址
            url: config.base_server() + 'companys/tree?access_token=' + config.getToken().access_token,
            // 访问数据接口参数
            param: {parentId: '0'}
        }).lrselectSetFirst();

        $('#planTime').lrdate({
            dfdata: [
                {
                    name: '近1个月', begin: function () {
                        return learun.getDate('yyyy-MM-dd 00:00:00', 'm', -1)
                    }, end: function () {
                        return learun.getDate('yyyy-MM-dd 23:59:59')
                    }
                },
                {
                    name: '近3个月', begin: function () {
                        return learun.getDate('yyyy-MM-dd 00:00:00', 'm', -3)
                    }, end: function () {
                        return learun.getDate('yyyy-MM-dd 23:59:59')
                    }
                },
                {
                    name: '近1年', begin: function () {
                        return learun.getDate('yyyy-MM-dd 00:00:00', 'm', -12)
                    }, end: function () {
                        return learun.getDate('yyyy-MM-dd 23:59:59')
                    }
                },
            ],
            // 月
            mShow: false,
            premShow: false,
            // 季度
            jShow: false,
            prejShow: false,
            // 年
            ysShow: false,
            yxShow: false,
            preyShow: false,
            yShow: false,
            // 默认
            dfvalue: '2',
            selectfn: function (begin, end) {
                startTime = begin;
                endTime = end;
            }
        });

        $('#gridTable').css("width", $('.lr-form-wrap').width() - 60);

        //加载明细计划表格
        initGridDetail();
        //加载明细计划表格
        initGridTarget();

        //禁用输入框自动填充
        $("input[type='text']").each(function (index) {
            this.autocomplete = "off";
        });
    };
    //设置表单不可编辑
    setFormDisabled = function (wfType, upload) {
        if (!!wfType && wfType == 100) {
            $('#form').find('input,textarea,select').attr('disabled', 'disabled');
            if (upload != '1') {
                $('#lrUploader_uploadBtn_files').hide();
            }
        }
    };
    // 获取表单数据
    getFormData = function () {
        var formData = $('#form').lrGetFormData();

        var postData = formData;
        var detailData = [];
        var detailDataTmp = $('#gridtable_detail').jfGridGet('rowdatas');

        for (var i = 0, l = detailDataTmp.length; i < l; i++) {
            if (!!detailDataTmp[i]['name']) {
                // if (!detailDataTmp[i].money) {
                //     learun.alert.error('第' + (i + 1) + '行金额非法');
                //     return;
                // }
                detailDataTmp[i].sort = i;
                detailData.push(detailDataTmp[i]);
            }
        }
        postData.details = detailData;

        var targetData = [];
        var targetDataTmp = $('#gridtable_target').jfGridGet('rowdatas');

        for (var i = 0, l = targetDataTmp.length; i < l; i++) {
            if (!!targetDataTmp[i]['name']) {
                // if (!detailDataTmp[i].money) {
                //     learun.alert.error('第' + (i + 1) + '行金额非法');
                //     return;
                // }
                targetDataTmp[i].sort = i;
                targetData.push(targetDataTmp[i]);
            }
        }
        postData.targets = targetData;

        postData.id = parent.processId;
        return postData;
    };
    // 设置表单数据
    setFormData = function (processId, wfType, checkPermission, upload) {
        if (processId) {
            $('#filesPolicy').lrUploader({isView: false});
            $('#filesOther').lrUploader({isView: false, processId: processId});

            $.lrSetForm(config.base_server() + 'projectapplys/findByProcessId?processId=' + processId, function (data) {
                console.log(data);
                if (data != null) {
                    isUpdate = true;
                    $('#form').lrSetFormData(data);
                    $("#processCode").html(data.processCode);

                    $('#gridtable_detail').jfGridSet('refreshdata', data.details);
                    if (data.details.length < 6) {
                        for (var i = data.details.length; i < 6; i++) {
                            $('#gridtable_detail').jfGridSet('addRow', {});
                        }
                    }
                    $('#gridtable_target').jfGridSet('refreshdata', data.targets);
                    if (data.targets.length < 6) {
                        for (var i = data.targets.length; i < 6; i++) {
                            $('#gridtable_target').jfGridSet('addRow', {});
                        }
                    }
                }
                setPbtn(wfType, checkPermission);
            });
        } else {
            setPbtn(wfType, checkPermission);
        }
        setFormDisabled(wfType, upload);
    };
    // 验证数据是否填写完整
    validForm = function (code) {
        if (!$('#form').lrValidform()) {
            return false;
        }
        if (code == 'create') {
            if ($('#files').find('.lrUploader-input').text() == '') {
                learun.alert.error("请上传【附件】");
                return false;
            }
        }

        return true;
    };
    validBusinessData = function () {
        return true;
    }
    // 保存调用函数
    save = function (processId, force, callBack, i) {
        var keyValue = "";

        if (isUpdate) {
            keyValue = processId;
        }

        var formData = $('#form').lrGetFormData();

        var postData = formData;
        var detailData = [];
        var detailDataTmp = $('#gridtable_detail').jfGridGet('rowdatas');

        for (var i = 0, l = detailDataTmp.length; i < l; i++) {
            if (!!detailDataTmp[i]['name']) {
                // if (!detailDataTmp[i].money) {
                //     learun.alert.error('第' + (i + 1) + '行金额非法');
                //     return;
                // }
                detailDataTmp[i].sort = i;
                detailData.push(detailDataTmp[i]);
            }
        }
        postData.details = detailData;

        var targetData = [];
        var targetDataTmp = $('#gridtable_target').jfGridGet('rowdatas');

        for (var i = 0, l = targetDataTmp.length; i < l; i++) {
            if (!!targetDataTmp[i]['first']) {
                // if (!detailDataTmp[i].money) {
                //     learun.alert.error('第' + (i + 1) + '行金额非法');
                //     return;
                // }
                targetDataTmp[i].sort = i;
                targetData.push(targetDataTmp[i]);
            }
        }
        postData.companyId = companyId;
        postData.departmentName = $("#departmentId").lrselectGetEx().text;
        postData.targets = targetData;
        postData.id = parent.processId;
        postData.startTime = startTime;
        postData.endTime = endTime;

        $.lrSaveForm(config.base_server() + 'projectapplys/saveOrUpdate?keyValue=' + keyValue + '&force=' + force + '&access_token=' + config.getToken().access_token, JSON.stringify(postData), function (res) {
            // 保存成功后才回调
            if (!!callBack) {
                callBack(res, i);
            }
        });
    };

    // 保存调用函数
    saveDraft = function (processId, force, callBack, i) {
        var keyValue = "";

        if (isUpdate) {
            keyValue = processId;
        }

        var formData = $('#form').lrGetFormData();
        var postData = formData;
        var detailData = [];
        var detailDataTmp = $('#gridtable_detail').jfGridGet('rowdatas');

        for (var i = 0, l = detailDataTmp.length; i < l; i++) {
            if (!!detailDataTmp[i]['name']) {
                // if (!detailDataTmp[i].money) {
                //     learun.alert.error('第' + (i + 1) + '行金额非法');
                //     return;
                // }
                detailDataTmp[i].sort = i;
                detailData.push(detailDataTmp[i]);
            }
        }
        postData.details = detailData;

        var targetData = [];
        var targetDataTmp = $('#gridtable_target').jfGridGet('rowdatas');

        for (var i = 0, l = targetDataTmp.length; i < l; i++) {
            if (!!targetDataTmp[i]['first']) {
                // if (!detailDataTmp[i].money) {
                //     learun.alert.error('第' + (i + 1) + '行金额非法');
                //     return;
                // }
                targetDataTmp[i].sort = i;
                targetData.push(targetDataTmp[i]);
            }
        }
        postData.companyId = companyId;
        postData.departmentName = $("#departmentId").lrselectGetEx().text;
        postData.targets = targetData;
        postData.id = parent.processId;
        postData.startTime = startTime;
        postData.endTime = endTime;

        $.lrSaveForm(config.base_server() + 'projectapplys/saveOrUpdate?keyValue=' + keyValue + '&force=' + force + '&access_token=' + config.getToken().access_token, JSON.stringify(postData), function (res) {
            // 保存成功后才回调
            if (!!callBack) {
                callBack(res, i);
            }
        });
    };


    // 设置父级窗口的按钮
    function setPbtn(wfType, checkPermission) {
        if (!!wfType && wfType == 100 && checkPermission == true) { //审核
            // $('#lr-layout-panel-right', window.parent.document).hide();
            $('#flow-force', window.parent.document).hide();
            $('#flow-projectinfo', window.parent.document).hide();
        } else if (!!wfType && wfType == 100 && checkPermission == false) { //查看
            $('#lr-layout-panel-right', window.parent.document).empty();
        } else {
            $('#release', window.parent.document).text('保存并送审');
            $('#savedraft', window.parent.document).text('保存');
            // $('.lr-form-item-title', window.parent.document).text('备注');
            //$('#savedraft', window.parent.document).hide();
            $('#verifyBill', window.parent.document).hide();
            $('#flow-projectinfo', window.parent.document).hide();
            $('#flow-force', window.parent.document).hide();
            $('#sign', window.parent.document).hide();
            $('#flow-title input', window.parent.document).val("项目立项申请");
            $('#flow-title input', window.parent.document).attr("readonly", "readonly");
            //$('#print', window.parent.document).hide();
        }
    }

    //加载明细计划表格
    function initGridDetail() {
        $('#gridtable_detail').jfGrid({
            headData: [
                {
                    label: '项目明细名称', name: 'name', width: 120, align: 'center',
                    edit: {
                        type: 'input'
                    }
                },
                {
                    label: '项目开支内容', name: 'content', width: 120, align: 'center',
                    edit: {
                        type: 'input'
                    }
                },
                {
                    label: '计量单位', name: 'unit', width: 60, align: 'center',
                    edit: {
                        type: 'input'
                    }
                },
                {
                    label: '单价', name: 'price', width: 90, align: 'center',
                    formatter: function (cellvalue) {
                        return $.formatMoney(cellvalue, 2);
                    },
                    edit: {
                        type: 'number',
                        change: function (data, num) {// 行数据和行号
                            if (!!data.count) {
                                data.money = data.price * data.count;
                                $('#gridtable_detail').jfGridSet('updateRow', num);
                            }
                        }
                    }
                },
                {
                    label: '采购数量', name: 'count', width: 60, align: 'center',
                    edit: {
                        type: 'number',
                        init: function (data, $edit) {// 在点击单元格的时候触发，可以用来初始化输入控件，行数据和控件对象
                        },
                        change: function (data, num) {// 行数据和行号
                            if (!!data.count) {
                                data.money = data.price * data.count;
                                $('#gridtable_detail').jfGridSet('updateRow', num);
                            }
                        }
                    }
                },
                {
                    label: '总价', name: 'money', width: 90, align: 'center', statistics: true,
                    formatter: function (cellvalue) {
                        return $.formatMoney(cellvalue, 2);
                    },
                },
                {
                    label: '项目执行时间', name: 'actionTime', width: 100, align: 'center',
                    edit: {
                        type: 'datatime',
                        dateformat: '0',       // 0:yyyy-MM-dd;1:yyyy-MM-dd HH:mm,格式
                        init: function (data, $edit) {// 在点击单元格的时候触发，可以用来初始化输入控件，行数据和控件对象
                        },
                        change: function (data, num) {// 行数据和行号
                        }
                    }
                },
                {
                    label: '项目测算依据或说明', name: 'remark', width: 100, align: 'left',
                    edit: {
                        type: 'input',
                    }
                }
            ],
            isEdit: true,
            isMultiselect: true,
            // onAddRow: function (row, rows) {//行数据和所有行数据
            //
            // },
            // onMinusRow: function (row, rows) {//行数据和所有行数据
            //
            // },
            // beforeMinusRow: function (row) {// 行数据 返回false 则不许被删除
            //     return true;
            // }
        });
        $('#gridtable_detail').jfGridSet('addRow', {});
        $('#gridtable_detail').jfGridSet('addRow', {});
        $('#gridtable_detail').jfGridSet('addRow', {});
        $('#gridtable_detail').jfGridSet('addRow', {});
        $('#gridtable_detail').jfGridSet('addRow', {});
        $('#gridtable_detail').jfGridSet('addRow', {});
    }

    //加载项目绩效目标表格
    function initGridTarget() {
        $('#gridtable_target').jfGrid({
            headData: [
                {
                    label: '一级指标', name: 'first', width: 160, align: 'center',
                    edit: {
                        type: 'select',
                        init: function (data, $edit) {// 在点击单元格的时候触发，可以用来初始化输入控件，行数据和控件对象

                        },
                        change: function (data, num, selectrow) {// 行数据和行号
                            if (data.columnKey == "1") {
                                data.isNullable = '0';
                                $('#gridtable').jfGridSet('updateRow', num);
                            }
                        },
                        op: {// 下拉框设置参数 和 lrselect一致
                            data: [
                                {'id': '产出指标', 'text': '产出指标'},
                                {'id': '效益指标', 'text': '效益指标'}
                            ]
                        }
                    }
                },
                {
                    label: '二级指标', name: 'second', width: 120, align: 'center',
                    edit: {
                        type: 'input'
                    }
                },
                {
                    label: '三级指标', name: 'three', width: 120, align: 'center',
                    edit: {
                        type: 'input'
                    }
                },
                {
                    label: '实施周期指标值', name: 'implTarget', width: 120, align: 'center',
                    edit: {
                        type: 'input'
                    }
                },
                {
                    label: '年度指标值', name: 'yearTarget', width: 120, align: 'center',
                    edit: {
                        type: 'input'
                    }
                },
                {
                    label: '备注', name: 'remark', width: 120, align: 'left',
                    edit: {
                        type: 'input',
                    }
                }
            ],
            isEdit: true,
            isMultiselect: true,
            // onAddRow: function (row, rows) {//行数据和所有行数据
            //
            // },
            // onMinusRow: function (row, rows) {//行数据和所有行数据
            //
            // },
            // beforeMinusRow: function (row) {// 行数据 返回false 则不许被删除
            //     return true;
            // }
        });
        $('#gridtable_target').jfGridSet('addRow', {});
        $('#gridtable_target').jfGridSet('addRow', {});
        $('#gridtable_target').jfGridSet('addRow', {});
        $('#gridtable_target').jfGridSet('addRow', {});
        $('#gridtable_target').jfGridSet('addRow', {});
        $('#gridtable_target').jfGridSet('addRow', {});
    }
}
